{% extends 'base/base.html' %}

{% block title %}优化版仪表盘 - 多用户报警系统{% endblock %}

{% block extra_css %}
<style>
    /* 添加加载动画 */
    .loading-spinner {
        display: none;
        text-align: center;
        padding: 20px;
    }
    
    .loading-spinner.show {
        display: block;
    }
    
    .spinner {
        border: 4px solid rgba(0, 0, 0, 0.1);
        width: 36px;
        height: 36px;
        border-radius: 50%;
        border-left-color: #09f;
        margin: 0 auto;
        animation: spin 1s linear infinite;
    }
    
    @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }
    
    /* 添加消息列表优化样式 */
    .message-table-container {
        position: relative;
        min-height: 300px;
    }
    
    /* 添加懒加载占位符 */
    .lazy-load-placeholder {
        background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
        background-size: 200% 100%;
        animation: shimmer 1.5s infinite;
        border-radius: 4px;
        height: 20px;
        margin: 8px 0;
    }
    
    @keyframes shimmer {
        0% { background-position: -200% 0; }
        100% { background-position: 200% 0; }
    }
    
    /* 优化表格单元格间距 */
    .message-table-container .table td,
    .message-table-container .table th {
        padding: 12px 16px;
        vertical-align: middle;
    }
    
    /* 优化响应式布局 */
    @media (max-width: 768px) {
        .card-body {
            padding: 15px;
        }
        
        .message-table-container .table td,
        .message-table-container .table th {
            padding: 8px;
            font-size: 14px;
        }
    }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <!-- 页面标题 -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h1 class="h2">
            <i class="fa fa-tachometer-alt" aria-hidden="true"></i> 优化版仪表盘
            <span class="badge bg-success ml-2">⚡</span>
        </h1>
        <div>
            <a href="{% url 'projects:project_create' %}" class="btn btn-primary">
                <i class="fa fa-plus" aria-hidden="true"></i> 创建项目
            </a>
            {% if is_super_admin %}
            <a href="{% url 'tasks:scheduled_task_list' %}" class="btn btn-success ml-2">
                <i class="fa fa-clock" aria-hidden="true"></i> 定时任务管理
            </a>
            {% endif %}
        </div>
    </div>

    <!-- 优化提示 -->
    <div class="alert alert-info alert-dismissible fade show mb-4" role="alert">
        <strong>优化提示：</strong> 此版本仪表盘采用了多项性能优化，包括数据缓存、异步加载和懒加载，大大提升了页面加载速度。
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>

    <!-- 统计卡片 - 服务端渲染 -->
    <div class="row mb-4">
        <div class="col-md-3">
            <div class="card bg-primary text-white">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <div>
                            <h4 class="card-title">{{ stats.total_messages }}</h4>
                            <p class="card-text">总消息数</p>
                        </div>
                        <div class="align-self-center">
                            <i class="fa fa-envelope fa-2x"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card bg-warning text-white">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <div>
                            <h4 class="card-title">{{ stats.pending_messages }}</h4>
                            <p class="card-text">待处理</p>
                        </div>
                        <div class="align-self-center">
                            <i class="fa fa-clock fa-2x"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card bg-success text-white">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <div>
                            <h4 class="card-title">{{ stats.processed_messages }}</h4>
                            <p class="card-text">已处理</p>
                        </div>
                        <div class="align-self-center">
                            <i class="fa fa-check fa-2x"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card bg-info text-white">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <div>
                            <h4 class="card-title">{{ stats.total_projects }}</h4>
                            <p class="card-text">项目数量</p>
                        </div>
                        <div class="align-self-center">
                            <i class="fa fa-project-diagram fa-2x"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <!-- 左侧：消息列表 - 客户端异步加载 -->
        <div class="col-lg-8">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">
                        <i class="fa fa-list" aria-hidden="true"></i> 最近消息
                        <span class="text-muted text-sm ml-2">(仅显示最近7天)</span>
                    </h5>
                    <span class="badge bg-secondary">{{ stats.total_messages }}</span>
                </div>
                <div class="card-body p-0">
                    <div id="messageTableContainer" class="message-table-container">
                        <!-- 初始加载占位符 -->
                        <div class="loading-spinner show">
                            <div class="spinner"></div>
                            <p class="mt-2">正在加载消息...</p>
                        </div>
                        
                        <!-- 消息列表将通过JavaScript动态生成 -->
                        <div id="messageTable" style="display: none;">
                            <div class="table-responsive">
                                <table class="table table-hover mb-0">
                                    <thead class="table-light">
                                        <tr>
                                            <th width="20%">项目</th>
                                            <th width="25%">消息内容</th>
                                            <th width="10%">类型</th>
                                            <th width="10%">状态</th>
                                            <th width="10%">创建时间</th>
                                            <th width="15%">处理时间/处理人</th>
                                            <th width="10%">操作</th>
                                        </tr>
                                    </thead>
                                    <tbody id="messageTableBody">
                                        <!-- 消息行将通过JavaScript动态生成 -->
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 分页控件 -->
                    <div id="paginationControls" class="mt-3" style="display: none;">
                        <nav aria-label="Page navigation">
                            <ul class="pagination justify-content-center">
                                <li id="prevPage" class="page-item">
                                    <a class="page-link" href="#" aria-label="Previous">
                                        <span aria-hidden="true">&laquo;</span>
                                    </a>
                                </li>
                                <li id="nextPage" class="page-item">
                                    <a class="page-link" href="#" aria-label="Next">
                                        <span aria-hidden="true">&raquo;</span>
                                    </a>
                                </li>
                            </ul>
                            <div class="text-center mt-2 text-muted">
                                <span id="pageInfo">第 <span id="currentPage">1</span> 页，共 <span id="totalPages">1</span> 页</span>
                            </div>
                        </nav>
                    </div>
                </div>
            </div>
        </div>

        <!-- 右侧：项目列表和公告 -->
        <div class="col-lg-4">
            <!-- 项目列表 - 服务端渲染 -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0">
                        <i class="fa fa-project-diagram" aria-hidden="true"></i> 我的项目
                        <span class="text-muted text-sm ml-2">(最近10个)</span>
                    </h5>
                </div>
                <div class="card-body p-0">
                    {% if user_projects %}
                        <div class="list-group list-group-flush">
                            {% for project in user_projects %}
                                <a href="{% url 'projects:project_detail' project.id %}"
                                   class="list-group-item list-group-item-action d-flex justify-content-between align-items-center">
                                    <div>
                                        <h6 class="mb-1">{{ project.name }}</h6>
                                        <small class="text-muted">{{ project.description|truncatechars:30 }}</small>
                                    </div>
                                    <span class="badge bg-primary rounded-pill">
                                        {{ project_stats|get:project.id|get:'total_messages'|default:0 }}
                                    </span>
                                </a>
                            {% endfor %}
                        </div>
                    {% else %}
                        <div class="text-center py-4">
                            <i class="fa fa-folder-open fa-2x text-muted mb-2"></i>
                            <p class="text-muted">暂无项目</p>
                            <a href="{% url 'projects:project_create' %}" class="btn btn-primary btn-sm">
                                <i class="fa fa-plus"></i> 创建项目
                            </a>
                        </div>
                    {% endif %}
                </div>
            </div>

            <!-- 公告列表 - 服务端渲染 -->
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">
                        <i class="fa fa-bullhorn" aria-hidden="true"></i> 公告
                    </h5>
                </div>
                <div class="card-body p-0">
                    {% if announcements %}
                        <div class="list-group list-group-flush">
                            {% for announcement in announcements %}
                                <div class="list-group-item">
                                    <div class="d-flex w-100 justify-content-between">
                                        <h6 class="mb-1">{{ announcement.title }}</h6>
                                        <small class="text-muted">{{ announcement.created_at|date:"m-d" }}</small>
                                    </div>
                                    <p class="mb-1 small">{{ announcement.content|truncatechars:50 }}</p>
                                    {% if announcement.tags.all %}
                                        <div class="mt-1">
                                            {% for tag in announcement.tags.all %}
                                                <span class="badge bg-secondary me-1">{{ tag.name }}</span>
                                            {% endfor %}
                                        </div>
                                    {% endif %}
                                </div>
                            {% endfor %}
                        </div>
                        <div class="card-footer text-center">
                            <a href="{% url 'projects:announcement_list' %}" class="btn btn-outline-primary btn-sm">
                                查看所有公告
                            </a>
                        </div>
                    {% else %}
                        <div class="text-center py-4">
                            <i class="fa fa-bullhorn fa-2x text-muted mb-2"></i>
                            <p class="text-muted">暂无公告</p>
                        </div>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    // 页面加载完成后执行
    document.addEventListener('DOMContentLoaded', function() {
        // 当前页码
        let currentPage = 1;
        let totalPages = 1;
        
        // 异步加载消息列表
        loadMessages(currentPage);
        
        // 上一页按钮点击事件
        document.getElementById('prevPage').addEventListener('click', function(e) {
            e.preventDefault();
            if (currentPage > 1) {
                loadMessages(currentPage - 1);
            }
        });
        
        // 下一页按钮点击事件
        document.getElementById('nextPage').addEventListener('click', function(e) {
            e.preventDefault();
            if (currentPage < totalPages) {
                loadMessages(currentPage + 1);
            }
        });
        
        // 定期刷新数据
        setInterval(function() {
            refreshDashboardStats();
        }, 30000); // 30秒刷新一次
    });
    
    // 加载消息列表
    function loadMessages(page) {
        // 显示加载动画
        document.querySelector('.loading-spinner').classList.add('show');
        document.getElementById('messageTable').style.display = 'none';
        document.getElementById('paginationControls').style.display = 'none';
        
        // 发起API请求
        fetch(`/projects/api/message-list/?page=${page}&page_size=30`) 
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // 更新当前页码和总页数
                    currentPage = data.current_page;
                    totalPages = data.total_pages;
                    
                    // 更新页面信息
                    document.getElementById('currentPage').textContent = currentPage;
                    document.getElementById('totalPages').textContent = totalPages;
                    
                    // 更新上一页/下一页按钮状态
                    document.getElementById('prevPage').classList.toggle('disabled', !data.has_previous);
                    document.getElementById('nextPage').classList.toggle('disabled', !data.has_next);
                    
                    // 渲染消息列表
                    renderMessageTable(data.messages);
                    
                    // 显示消息列表和分页控件
                    document.querySelector('.loading-spinner').classList.remove('show');
                    document.getElementById('messageTable').style.display = 'block';
                    document.getElementById('paginationControls').style.display = 'block';
                } else {
                    console.error('加载消息失败:', data.error);
                    showError('加载消息失败，请稍后重试');
                }
            })
            .catch(error => {
                console.error('加载消息时发生错误:', error);
                showError('加载消息时发生错误，请稍后重试');
            });
    }
    
    // 渲染消息列表表格
    function renderMessageTable(messages) {
        const tableBody = document.getElementById('messageTableBody');
        tableBody.innerHTML = '';
        
        if (messages.length === 0) {
            // 显示空状态
            const emptyRow = document.createElement('tr');
            emptyRow.innerHTML = `
                <td colspan="7" class="text-center py-5">
                    <i class="fa fa-inbox fa-3x text-muted mb-3"></i>
                    <h5 class="text-muted">暂无消息</h5>
                    <p class="text-muted">您参与的项目还没有收到任何消息</p>
                </td>
            `;
            tableBody.appendChild(emptyRow);
        } else {
            // 渲染消息行
            messages.forEach(message => {
                const row = document.createElement('tr');
                
                // 格式化日期
                const createdAt = new Date(message.created_at);
                const formattedCreatedAt = `${createdAt.getMonth() + 1}-${createdAt.getDate()} ${createdAt.getHours().toString().padStart(2, '0')}:${createdAt.getMinutes().toString().padStart(2, '0')}`;
                
                let processedInfo = '<span class="text-muted">-</span>';
                if (message.processed_at) {
                    const processedAt = new Date(message.processed_at);
                    const formattedProcessedAt = `${processedAt.getMonth() + 1}-${processedAt.getDate()} ${processedAt.getHours().toString().padStart(2, '0')}:${processedAt.getMinutes().toString().padStart(2, '0')}`;
                    processedInfo = `
                        <small class="text-muted">
                            ${formattedProcessedAt}<br>
                            <span class="text-primary">${message.processed_by || '系统'}</span>
                        </small>
                    `;
                }
                
                // 构建操作按钮
                let actionButtons = `
                    <div class="btn-group btn-group-sm gap-1">
                        <a href="/projects/${message.project_id}/message/${message.id}/" 
                            class="btn btn-outline-primary btn-sm" title="查看详情">
                             <i class="fa fa-eye"></i>
                         </a>
                    </div>
                `;
                
                if (message.status === 'pending') {
                    actionButtons = `
                        <div class="btn-group btn-group-sm gap-1">
                            <a href="/projects/${message.project_id}/message/${message.id}/" 
                                class="btn btn-outline-primary btn-sm" title="查看详情">
                                 <i class="fa fa-eye"></i>
                             </a>
                             <form method="post" action="/projects/${message.project_id}/message/${message.id}/toggle-status/" class="d-inline">
                                {% csrf_token %}
                                <button type="submit" class="btn btn-outline-success btn-sm" title="标记为已处理">
                                    <i class="fa fa-check"></i>
                                </button>
                            </form>
                        </div>
                    `;
                }
                
                // 设置行内容
                row.innerHTML = `
                    <td>
                        <a href="/projects/${message.project_id}/" class="text-decoration-none">
                            <strong>${message.project_name}</strong>
                        </a>
                    </td>
                    <td>
                        <div class="text-truncate" style="max-width: 250px;">
                            ${message.content}
                        </div>
                    </td>
                    <td>
                        <span class="badge ${message.message_type === 'webhook' ? 'bg-primary' : message.message_type === 'announcement' ? 'bg-warning' : 'bg-info'}">
                            ${message.message_type_display || message.message_type}
                        </span>
                    </td>
                    <td>
                        <span class="badge ${message.status === 'pending' ? 'bg-warning' : 'bg-success'}">
                            ${message.status === 'pending' ? '待处理' : '已处理'}
                        </span>
                    </td>
                    <td>
                        <small class="text-muted">${formattedCreatedAt}</small>
                    </td>
                    <td>
                        ${processedInfo}
                    </td>
                    <td>
                        ${actionButtons}
                    </td>
                `;
                
                tableBody.appendChild(row);
            });
        }
    }
    
    // 刷新仪表盘统计数据
    function refreshDashboardStats() {
        fetch('/projects/api/dashboard-data/')
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // 更新统计卡片
                    document.querySelectorAll('.card-title')[0].textContent = data.stats.total_messages;
                    document.querySelectorAll('.card-title')[1].textContent = data.stats.pending_messages;
                    document.querySelectorAll('.card-title')[2].textContent = data.stats.processed_messages;
                    document.querySelectorAll('.card-title')[3].textContent = data.stats.total_projects;
                    
                    // 如果当前没有显示消息列表，可以考虑更新项目列表中的消息计数
                    if (document.querySelector('.loading-spinner').classList.contains('show')) {
                        // 更新项目列表中的消息计数
                        updateProjectMessageCounts(data.projects);
                    }
                }
            })
            .catch(error => {
                console.error('刷新统计数据时发生错误:', error);
            });
    }
    
    // 更新项目列表中的消息计数
    function updateProjectMessageCounts(projects) {
        const projectLinks = document.querySelectorAll('.list-group-item-action');
        projectLinks.forEach(link => {
            const projectName = link.querySelector('h6').textContent;
            const projectData = projects.find(p => p.name === projectName);
            if (projectData) {
                const badge = link.querySelector('.badge');
                badge.textContent = projectData.message_count;
            }
        });
    }
    
    // 显示错误消息
    function showError(message) {
        // 隐藏加载动画
        document.querySelector('.loading-spinner').classList.remove('show');
        
        // 显示错误消息
        const tableContainer = document.getElementById('messageTableContainer');
        tableContainer.innerHTML = `
            <div class="text-center py-5">
                <i class="fa fa-exclamation-circle fa-3x text-danger mb-3"></i>
                <h5 class="text-danger">${message}</h5>
                <button class="btn btn-primary mt-3" onclick="loadMessages(1)">
                    <i class="fa fa-refresh"></i> 重试
                </button>
            </div>
        `;
    }
</script>
{% endblock %}